package com.ugoodtech.mdcc.web.controller;

import com.ugoodtech.mdcc.web.dto.JsonResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/uploadExcel")
public class UploadStationExcel extends BaseController{

    @RequestMapping(value = "station", method = RequestMethod.POST)
    public JsonResponse uploadExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        isUserLogin();
        //file.isEmpty(); 判断图片是否为空
        //file.getSize(); 图片大小进行判断
        String templetPath = request.getSession().getServletContext().getRealPath("");
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);

        // 获取文件的后缀名,比如图片的jpeg,png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);

        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:" + fileName);
        File dest = new File(templetPath + "/import/" + fileName);
        try {
            file.transferTo(dest);
            return JsonResponse.successResponseWithData(fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonResponse.errorResponseWithError("fail to save file", fileName);
    }

}
